package com.dbapp.garden.controller.contract;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.config.security.PermissionUser;
import com.dbapp.garden.entity.GardenContractPackageInfo;
import com.dbapp.garden.service.IGardenContractPackageInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author gangzi 
 */
@Controller
public class ContractPackageController extends BaseContractController {

    @Autowired
    IGardenContractPackageInfoService packageService;

    @GetMapping("/contractpackage_basic")
    @PreAuthorize("hasAuthority('PERMISSION_CONTRACT_SETTING')")
    public String toBasicInfoPage(HttpServletRequest request) {
        return "contract/contractpackage_basic";
    }

    @PostMapping("/contactpackagelist")
    @ResponseBody
	@PreAuthorize("hasAuthority('PERMISSION_CONTRACT_BASIC_INFO_VIEW') or hasAuthority('PERMISSION_CONTRACT_SETTING')")
    public Map<String, ?> contractPackageList(HttpServletRequest request, String param) {
        int gardenId = this.getSelfGardenId(request);
        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");
        System.out.println("search=>" + this.changeObjToStr(paramMap));
        List<GardenContractPackageInfo> contractPackageList = packageService.getContractPackageList(gardenId, sSearch, iDisplayStart, iDisplayLength);
        int count = packageService.getContractPackageCount(gardenId, sSearch);

        List<Map> ret = new ArrayList<Map>();
        if (contractPackageList != null)
            for (GardenContractPackageInfo pack : contractPackageList) {
                Map temp = this.changeObjToMap(pack);
                if (temp == null) continue;
                temp.put("packageTypeName", pack.getPackageType().intValue() == 1 ? "课程套餐" : "托班套餐");
                ret.add(temp);
            }
        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, ret, "");
    }

    @PostMapping("/contractpackage")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CONTRACT_BASIC_INFO_ADD')")
    public Map<String, ?> addContractPackage(@SessionAttribute("user") PermissionUser user, @RequestBody @Valid GardenContractPackageInfo packageInfo) {
        if (packageInfo == null) {
            return RenderJSON.makeStandMap(2, "对不起，添加失败！", "error");
        }

        if (StringUtils.isBlank(packageInfo.getContractPackageName())) {
            return RenderJSON.makeStandMap(2, "对不起，添加失败,合同套餐名称为空！", "error");
        }

        packageInfo.setCreateDate(new Date());
        packageInfo.setUpdateDate(new Date());

        packageInfo.setGarden_id(user.getGardenId());

        packageInfo = packageService.saveContractPackage(packageInfo);
        if (packageInfo != null) {
            return RenderJSON.makeStandMap(1, "恭喜您，添加成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
        }
    }

    @DeleteMapping("/contractpackage/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CONTRACT_BASIC_INFO_DELETE')")
    public Map<String, ?> deleteContractPackage(@SessionAttribute("user") PermissionUser user, @PathVariable("id") Integer id) {
        if (id == null){
            return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
        }
        GardenContractPackageInfo packageInfo = packageService.findById(id);
        if (packageInfo == null){
            return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
        }

        if (!packageInfo.getGarden_id().equals(user.getGardenId())){
            return RenderJSON.makeStandMap(1, "对不起，无操作权限！", "error");
        }

        int result = packageService.deleteContractPackageInfo(id);
        if (result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，删除成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
        }
    }

    @PutMapping("/contractpackage/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CONTRACT_BASIC_INFO_EDIT')")
    public Map<String, ?> editContractPackage(@SessionAttribute("user") PermissionUser user, @PathVariable("id") Integer id, @RequestBody @Valid GardenContractPackageInfo packageInfo) {
        if (id == null || packageInfo == null){
            return RenderJSON.makeStandMap(2, "对不起，编辑失败,请检查参数！", "error");
        }
        if (StringUtils.isBlank(packageInfo.getContractPackageName())){
            return RenderJSON.makeStandMap(2, "对不起，编辑失败,合同套餐名称为空！", "error");
        }

        GardenContractPackageInfo pInfo = packageService.findById(id);
        if (pInfo == null ){
            return RenderJSON.makeStandMap(2, "对不起，合同套餐不存在，编辑失败！", "error");
        }
        if (!pInfo.getGarden_id().equals(user.getGardenId())){
            return RenderJSON.makeStandMap(2, "对不起，无操作权限！", "error");
        }
        packageInfo.setId(id);
        packageInfo.setUpdateDate(new Date());
        packageInfo.setGarden_id(user.getGardenId());
        packageInfo = packageService.saveContractPackage(packageInfo);
        if (packageInfo != null) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }
    }
}
